import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import eslintPlugin from 'vite-plugin-eslint'
import vueJsx from '@vitejs/plugin-vue-jsx'
import path from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons' // 版本不同引入方式不同
// https://vitejs.dev/config/
export default defineConfig(async ({ command }) => {
  // const env = loadEnv(mode, process.cwd(), '')
  const config = {
    base: './', // env.VITE_BASE_API,
    resolve: {
      // 别名配置
      alias: {
        '@': path.join(__dirname, 'src'),
        '~': path.join(__dirname, 'src')
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@use "~/styles/element/index.scss" as *; @use "~/styles/index.scss" as *;'
        }
      }
    },
    plugins: [
      vue(),
      vueJsx(),
      eslintPlugin({
        cache: false, // 禁用eslint缓存
        include: ['src/**/*.js', 'src/**/*.jsx', 'src/*.vue', 'src/*.ts', 'src/*.ts']
      }),
      Components({
        resolvers: [
          ElementPlusResolver({
            importStyle: 'sass'
          }),
          IconsResolver({
            // 修改Icon组件前缀，不设置则默认为i,禁用则设置为false
            prefix: 'icon',
            // 指定collection，即指定为elementplus图标集ep <icon-ep-User />
            enabledCollections: ['ep']
          })
        ]
      }),
      AutoImport({
        resolvers: [
          ElementPlusResolver({
            importStyle: 'sass'
          })
        ]
      }),
      Icons({
        autoInstall: true
      }),
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons/svg')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]'
      })
    ]
  }
  if (command === 'build') { // 生产环境独有配置
    const buildConfig = {
      mode: 'production'
    }
    return Object.assign(config, buildConfig)
  } else {
    const devConfig = {
      mode: 'development',
      server: {
        host: '0.0.0.0',
        port: 8080,
        open: false,
        proxy: {
          '/api': {
            target: 'http://localhost:3000/admin',
            changeOrigin: true,
            rewrite: (path: string) => path.replace(/^\/api/, '')
          }
        }
      }
    }
    return Object.assign(config, devConfig)
  }
})
